# -*- coding: utf-8 -*-

"""
Module implementing MainWindow.
"""

from PyQt5.QtCore import pyqtSlot , QTimer
from PyQt5.QtWidgets import QMainWindow, QApplication

from Ui_form import Ui_MainWindow

import serial
import re, threading , time

class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor

        @param parent reference to the parent widget
        @type QWidget
        """
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        #create a timer
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.showNum)
        self.timer.start(200)
        
        self.terminal = 'welcome come to the serial '
        self.terminal = self.terminal + 'terminal'
        self.textBrowser.setText(self.terminal)
        

    @pyqtSlot()
    def on_pushButton_clicked(self):
        """
        Slot documentation goes here.
        """
        self.comname = self.lineEdit.text()
        if re.match(r'^com\d{1,2}$', self.comname):
            try :
                self.serial = serial.Serial(self.comname, 9600)
                self.alive = True;
                self.thread_read = threading.Thread(target=self.FirstReader);
                self.thread_read.start()
                self.terminal = ''
                self.label.setText('串口成功打开')
                

            except :
                 self.label.setText('com口打开失败，请检查打开com口')
        else:
            self.label.setText('输入格式错误,请重新输入')


    @pyqtSlot()
    def on_pushButton_2_clicked(self):
        """
        Slot documentation goes here.
        """

        self.alive = False
        self.thread_read.join()
        if self.serial.isOpen():
            self.serial.close()
            self.label.setText('串口关闭成功')



        # TODO: not implemented yet
        pass

    @pyqtSlot()
    def on_pushButton_3_clicked(self):
        self.terminal = ''
        
        
    def FirstReader(self):
        while self.alive:
            # 接收间隔
            time.sleep(0.1);
            
            try:
                
                n = self.serial.inWaiting();
                if n:
                    self.terminal = self.terminal + str(self.serial.read(n), encoding = "utf-8");
            except :
                print('read error')



        self.alive = False;
    def showNum(self):
        self.textBrowser.setText(self.terminal)




if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    myshow = MainWindow()
    myshow.show()
    sys.exit(app.exec_())
    

